#include "stdafx.h"
#include "thinker.hpp"
#include <pantheios/inserters/integer.hpp>
#include <boost/lexical_cast.hpp>

namespace FndGame2D {
  thinker::thinker_connection_map thinker::thinker_connections ;
  unsigned long thinker::current_connection_id(0UL) ;
  bool thinker::remove_connection(unsigned long id) {
    if(thinker_connections.find(id) == thinker_connections.end()) {
      pantheios::log_DEBUG(pantheios::integer(id) , " does not exist in thinker_connections\n") ;
      return false ;
    } else {
      thinker_connections[id].disconnect() ;
      thinker_connections.erase(id) ;
      return true ;
    }
  }

  bool thinker::add_connection(unsigned long id, sigc::connection& c) {
    if(!thinker_connections.insert(std::make_pair(id, c)).second) {
      pantheios::log_DEBUG(pantheios::integer(id),
			   " has exists! insert failed.\n") ;
      return false ;
    }
    return true ;
  }

  unsigned long thinker::create_connection_id() {
    return current_connection_id++ ;
  }

    thinker::thinker(const std::string& name): 
        m_name(make_a_valid_name(name)) {
        std::cout << "true name : " << m_name ;
        g_thinker_num++ ;
        message_handler.add_handle(ACTIVE, boost::bind(
                                       &thinker::set_thinker_active_message,
                                       this, _1)) ;
    }
    thinker::~thinker() {
        std::cout << "call uninit thinker " << name() << std::endl ;
        g_thinker_num-- ;
    }

    int thinker::get_total_created_thinker() {
        return g_thinker_num ;
    }
    const std::string& thinker::make_a_valid_name(const std::string& name) {
        static size_t temp_name = 0 ;
        static std::string temp_s ;
        std::cout << "name: " << name << std::endl ;
        if(name.empty()) {
            temp_s = boost::lexical_cast<std::string>(temp_name++) ;
            std::cout << "create name " << temp_s << std::endl ;
            return temp_s ;
        }
        return name ;
    }
    int thinker::g_thinker_num = 0 ;
    const std::string thinker::ACTIVE("active") ;
    const std::string thinker::THINKER_INIT("init") ; 
    bool thinker::set_thinker_active_message(const normal_thinker_message_type& msg) {
        try {
        m_is_active = boost::any_cast<bool>(msg.param) ;
        return true;
        } catch(const boost::bad_any_cast&) {
            return false ;
        }
    }

}

